package com.ljx.itbbs.server.mall.event.handler;

import com.ljx.itbbs.server.article.service.ResourceUserRelationService;
import com.ljx.itbbs.server.article.service.adapter.ArticleAdapter;
import com.ljx.itbbs.server.mall.domain.entity.CouponEntity;
import com.ljx.itbbs.server.mall.domain.entity.OrderEntity;
import com.ljx.itbbs.server.mall.domain.enums.OrderTypeEnum;
import com.ljx.itbbs.server.mall.event.OrderSubmitEvent;
import com.ljx.itbbs.server.mall.service.CouponRecordService;
import com.ljx.itbbs.server.mall.service.CouponService;
import com.ljx.itbbs.server.mall.service.OrderService;
import com.ljx.itbbs.server.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-03-29  22:44
 */
@Component
public class OrderSubmitEventHandler {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private CouponRecordService couponRecordService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private ResourceUserRelationService resourceUserRelationService;

    /**
     * 扣除用户积分
     * @param event
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = OrderSubmitEvent.class, fallbackExecution = true)
    public void updateUserIntegral(OrderSubmitEvent event){
        Long orderId = event.getOrderId();
        Long couponId = event.getCouponId();
        OrderEntity order = orderService.getOrder(orderId);
        Long userId = order.getUserId();
        Integer res  = order.getMoney();
        // 如果存在优惠券则需要扣除优惠券的积分，并且标注优惠券已经使用
        if (Objects.nonNull(couponId)){
            res = reduceCoupon(res, couponId);
            couponRecordService.useCoupon(couponId, userId);
        }
        userService.increaseUserIntegral(userId, -1 * res);
    }

    private Integer reduceCoupon(Integer res, Long couponId) {
        CouponEntity couponEntity = couponService.getById(couponId);
        return Math.max(0, res - couponEntity.getMoney());
    }

    /**
     * 不同类型的保存记录
     * @param event
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = OrderSubmitEvent.class, fallbackExecution = true)
    public void saveRecord(OrderSubmitEvent event){
        Long orderId = event.getOrderId();
        Long couponId = event.getCouponId();
        OrderEntity order = orderService.getOrder(orderId);
        Long userId = order.getUserId();
        if (order.getType().equals(OrderTypeEnum.ARTICLE_RESOURCE.getType())){
            // 若是文章资源，保存用户与文章资源之间的记录
            resourceUserRelationService.save(
                    ArticleAdapter.buildResourceRecordSave(userId, OrderTypeEnum.getTrueObjId(order.getObjId(), order.getType()))
            );
        }

    }

}
